//
//  InnerNewsListViewController.m
//  RSW.IOS
//
//  Created by zhaiqiuqiu on 17/1/16.
//  Copyright © 2017年 com.xtion.crm. All rights reserved.
//

#import "InnerNewsListViewController.h"
#import "InnerNewsCell.h"

NSString *const InnerNewsListViewControllerTitleParamKey = @"InnerNewsListViewControllerTitleParamKey";
NSString *const InnerNewsListViewControllerMobileParametersParamKey = @"InnerNewsListViewControllerMobileParametersParamKey";

@interface InnerNewsListViewController ()
{
    RSWDataOperation *_manager;
    
    NSDate *_lastUpdatetime;
    BOOL _bSearching;
    
    NSInteger _pageSize;
    NSInteger _pageIndex;
    
    NSMutableArray *_datas;
    NSMutableArray *_searchDatas;
    
    NSString *_column;
}
@end

@implementation InnerNewsListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self checkSession];
    
    NSString *title = self.param[InnerNewsListViewControllerTitleParamKey];
    [self setBackNavigateItemTitle:title];
  
    self.view.backgroundColor = [UIColor colorWithHex:mcrmSAASUISkinColorTextStylef1f4f7Color];
    
    [self initVariable];
    [self initUI];
    
    [_manager getInnerNewsSearch:_ctable.searchBar.searchText column:_column pageIndex:_pageIndex pageSize:_pageSize completion:^(NSInteger nResult, NSArray *list, NSError *error)
     {
         _bRefreshing = NO;
         
         [self requestComplete:nil funcationName:@"getInnerNews" result:nResult output:list error:error];
     }];
}

- (void)initVariable
{
    _manager = [[RSWDataOperation alloc]initWithDataOperationManagerDelegate:self];
    _searchDatas = [NSMutableArray new];
    _datas = [NSMutableArray new];
    
    _lastUpdatetime = [NSDate date];
    _pageIndex = 1;
    _pageSize = 20;
    
    _column = self.param[InnerNewsListViewControllerMobileParametersParamKey];
}

- (void)initUI
{
    [self createTableView:XUITabelViewStyleTypePlain|XUITabelViewStyleTypeRefresh|XUITabelViewStyleTypeSearch];
    _ctable.separatorExistFollowCell = NO;
    
    _ctable.searchBar.searchText = @"";
}

-(void)viewControllerWillDealloc
{
    [super viewControllerWillDealloc];
    [_manager terminateRequest];
}

-(NSMutableArray*)newsData;
{
    if(_bSearching == YES)
        return _searchDatas;
    
    return _datas;
}

-(void)requestComplete:(XMSDataOperationManager *)dom funcationName:(NSString *)szFuncationname result:(NSInteger)nResult output:(id)output error:(NSError *)error
{
    _bRefreshing = NO ;
    
    if([szFuncationname isEqualToString:@"getInnerNews"])
    {
        [self filterRequestResult:nResult defaultError:error noFilter:^(NSInteger requestResult)
         {
             switch(requestResult)
             {
                 case YES:
                 {
                     [_datas removeAllObjects];
                     
                     NSArray *ar = output;
                     
                     [_datas addObjectsFromArray:ar];
                     
                     if(_datas.count >= _pageSize)
                         [_ctable createLoadMoreView];
                     else
                         [_ctable removeLoadMoreView];
                     
                     [_ctable reloadData];
                     
                     break;
                 }
                 default:
                 {
                     [UIAlertView showErrorMsg:@"数据请求失败"];
                     break;
                 }
             }
         }];
    }
    else if([szFuncationname isEqualToString:@"getInnerNewsMore"])
    {
        [self filterRequestResult:nResult defaultError:error noFilter:^(NSInteger requestResult)
         {
             switch(requestResult)
             {
                 case YES:
                 {
                     if(((NSArray*)output).count > 0)
                     {
                         NSArray *ar = output;
                         
                         [_datas removeAllObjects];
                         [_datas addObjectsFromArray:ar];
                         
                         [_ctable reloadData];
                     }
                     else
                         [_ctable removeLoadMoreView];
                     
                     break;
                 }
                 default:
                 {
                     [UIAlertView showErrorMsg:@"数据获取失败"];
                     break;
                 }
             }
         }];
    }
}

#pragma mark --
#pragma mark -- tableView delegate

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    InnerNewsList * l = _datas[indexPath.row];
    if(l.rowHeight <= CaleRowHeightTag)
    {
        l.rowHeight = 80;
    }
    return l.rowHeight;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self newsData].count;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    InnerNewsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AttendanceListContent"];
    if(cell == nil)
    {
        cell = [[InnerNewsCell alloc]initWithReuseIdentifier:@"AttendanceListContent"];
    }
    
    InnerNewsList *bi = [self newsData][indexPath.row];
    
    cell.szTag = bi.newsId;
    
    cell.title = bi.title;
    cell.content = bi.tags;
    cell.createTime =  bi.createTime;
    cell.createUser = bi.createUser;
    //TODO
    //cell.headImage = bi.headImage;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    [UIViewController closeKeyBoard];
}

-(id)contentLastRefreshUpdateTimeOfTableView:(XUITableView *)tableview
{
    return _lastUpdatetime;
}

-(void)tableView:(XUITableView *)tableview refreshTableContent:(void (^)())asyncEndRefreshing
{
    if(_bRefreshing == YES)
        return;
    
    _bRefreshing = YES;
    [_manager stopRequest];
    
    _pageIndex = 1;
    [_manager getInnerNewsSearch:_ctable.searchBar.searchText column:_column pageIndex:_pageIndex pageSize:_pageSize completion:^(NSInteger nResult, NSArray *list, NSError *error)
     {
         if(nResult == YES)
             _lastUpdatetime = [NSDate date];
         
         _bRefreshing = NO;
         
         [self requestComplete:nil funcationName:@"getInnerNews" result:nResult output:list error:error];
     }];
}

#pragma mark --
#pragma mark -- loadMore delegate

- (void)loadMoreContentOfTableView:(XUITableView *)tableview
{
    if(_bLoadmoring == YES)
        return;
    
    if([_ctable.searchBar.searchText isEqualToString:@""] == NO)
    {
        _ctable.searchBar.searchText = @"";
        _bSearching = NO;
        [_searchDatas  removeAllObjects];
        [_ctable reloadData];
    }
    
    _bLoadmoring = YES;
    
    [tableview showLoadMoreStatus];
    
    _pageIndex ++;
    
     [_manager getInnerNewsSearch:_ctable.searchBar.searchText column:_column pageIndex:_pageIndex pageSize:_pageSize completion:^(NSInteger nResult, NSArray *list, NSError *error)
     {
         [tableview hideLoadMoreStatus];
         
         _bLoadmoring = NO;
         
         [self requestComplete:nil funcationName:@"getInnerNewsMore" result:nResult output:list error:error];
     }];
}

- (void)tableView:(XUITableView *)tableview didClickedLoadMoreFootView:(XUILoadMoreFootView *)sender
{
    [self loadMoreContentOfTableView:tableview];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
